<template>
	<view class="chat">
		<!-- 顶部标题 -->
		<view style="width: 100%;height: 10rpx;line-height: 10rpx;	display: flex;justify-content: space-between;">
			<u-popup :show="historyVisible" mode="left" @close="closeHistory" closeable>
				<view style="display: flex; width:300px;">
					<view style="font-size: 14px; line-height: 40px; flex:1; text-align: center;padding-right:5px">历史会话
					</view>
				</view>
				<view class="history-wraper">
					<view style="padding: 0px 20px; overflow-y: auto;">
						<view style="margin-bottom: 20px;">
							<view class="history_section">今天</view>
							<view style="background-color: #FFF; border-radius: 5px;  padding: 2px 5px;">
								<view style="margin-bottom: 10px;" v-for="(item,index) in history.today" :key="index"
									@click="handleViewHistory(item)">
									<view style="color: #8c8c8c; line-height:15px;">{{item.content}}</view>
								</view>
							</view>
						</view>
						<view>
							<view class="history_section">昨天</view>
							<view style="background-color: #FFF; border-radius: 5px;  padding: 2px 5px;">
								<view style="margin-bottom: 10px;" v-for="(item,index) in history.yesterday" :key="index"
									@click="handleViewHistory(item)">
									<view style="color: #8c8c8c;">{{item.content}}</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		<!--聊天消息滚动区域-->
		<scroll-view scroll-with-animation :style="{height: `${windowHeight-inputHeight-160}rpx`}" id="scrollview"
			scroll-y="true" :scroll-top="scrollTop" class="scroll-view">
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">

				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!--自己发送的问题-->
					<view v-if="item.sender==='user'"
						style="display: flex; justify-content: flex-end; margin: 5px 10px;">
						<view style="background-color: #409EFF; border-radius: 8px;">
							<view style="padding: 17rpx 20rpx; color: #f1f1f1;">
								<text style="word-break: break-all;">{{item.content}}</text>
							</view>
						</view>

						<view
							style="background-color:#409EFF; border-radius: 50px; width: 35px; height:35px;margin-top: 5px; margin-left: 10px;">
							<u-image width="30" height="30" src="@/static/user.png"></u-image>
						</view>
					</view>

					<!--机器人回复-->
					<view v-if="item.sender=='ai'"
						style="display: flex;flex-direction: column; align-items: start; padding-bottom: 10px; padding-left: 10px;">
						<view style="display: flex;height: 35px; line-height:35px;">
							<view><u-image width="30" height="30" src="@/static/logo.png"></u-image></view>
							<text>耒耜AI小助手</text>
						</view>
						<view
							style="display: flex; flex-direction: column;  background: #ebebeb;border-radius: 8px; margin-right: 10px;">
							<view style="padding: 17rpx 20rpx;">
								<u-parse :content="item.content" v-if="item.waiting==0"></u-parse>
								<u-loading-icon textSize="18" v-if="item.waiting==1"
									style="width: 40px;"></u-loading-icon>
							</view>

							<!--消息底部功能按钮-->
							<view style="margin: 5px; display: flex;justify-content:flex-end;"
								v-if="item.waiting==0 && item.actionVisible==true">
								<u-icon @click="copyContent(item.content)" name="order" color="#cfcfd1"
									size="22"></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!--历史会话-->
			
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight}rpx`}">
				<view class="uni-textarea" :style="isRecording? (isCancel ? 'background-color:#ff0000;color:#FFFFFF;':'background-color:#0ac6ff;color:#FFFFFF;'):'background-color:#f0f0f0;color:#333'">
					<view style="display:flex; width: 100%; position: absolute; bottom:110rpx;padding: 4px 6px;">
						<view
							style="padding: 4px 6px; height: 20px; line-height: 20rpx; font-size: 10px; color: #333; background-color: #e6e6e6; border-radius: 5px;"
							@click="openHistory">
							历史会话
						</view>
						
						<view
							style="padding: 4px 6px; margin-left:5px; height: 20px; line-height: 20rpx; font-size: 10px; color: #333; background-color: #e6e6e6; border-radius: 5px;"
							@click="createChat">
							新建会话
						</view>
					</view>

					
					<!--语音聊天-->
					<view v-if="inputType=='voice'" style="display: flex;">
						<view style="padding: 5px 10px;" v-if="!isRecording" @click="handleSwitchInputType">
							<u-icon name="mic" size="25" v-if="inputType=='text'"></u-icon>
							<u-icon custom-prefix="custom-icon-keyboard custom-icon" size="25" color="#888"
								v-if="inputType=='voice'"></u-icon>
						</view>
						<view style="flex: 1; height:65rpx;line-height: 65rpx; padding-top:0rpx;text-align: center; border-radius: 10px;" @touchstart="startRecording" @touchend="stopRecording" @touchmove="recordingMove">
							{{recordingTip}}
						</view>
						<view style="display: flex;"  v-if="!isRecording">
							<view style="padding: 5px 10px;" @click="handleSend">
								<u-icon custom-prefix="custom-icon-send custom-icon" :color="sendable()? '#333':'#d0d0d0'"  size="25"></u-icon>
							</view>
						</view>
					</view>				
					<!--文字聊天-->
					<u-input border="none" v-if="inputType=='text'" v-model="chatMsg" maxlength="300" confirm-type="send" @confirm="handleSend"
						placeholder="有什么问题可以随时问我哦!" :show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight"
						@focus="focus" @blur="blur" auto-height :focus="inputFocus">
						<template slot="prefix">
							<view style="padding: 5px 10px;" @click="handleSwitchInputType">
								<u-icon name="mic" size="25" v-if="inputType=='text'"></u-icon>
								<u-icon custom-prefix="custom-icon-keyboard custom-icon" size="20" color="#888"
									v-if="inputType=='voice'"></u-icon>
							</view>
						</template>
						<template slot="suffix">
							<view style="display: flex;">
								<view style="padding: 5px 5px; ">
									<u-icon name="plus-circle" size="25"></u-icon>
								</view>
								<view style="padding: 5px 10px;" @click="handleSend">
									<u-icon custom-prefix="custom-icon-send custom-icon" :color="sendable()? '#333':'#d0d0d0'" size="25"></u-icon>
								</view>
							</view>
						</template>
					</u-input>
					<u-toast ref="uToast"></u-toast>
				</view>
			</view>
		</view>
		
	</view>
</template>
<script>
	export default {
		data() {
			return {
				touchY:0,
				chatid:-1,
				isCancel:false,
				isRecording:false,
				recordingTip:'按住 说话',
				inputFocus:false,
				historyVisible: false,
				typeContent: '',
				typeResText: '',
				inputType: 'text',
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId: '',
				//发送的消息
				chatMsg: "",
				history: [],
				msgList: []
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight;
				//return this.keyboardHeight
			}
		},

		onLoad(option) {
			if (option.type == "history") {
				this.chatid=option.chatid;
				this.loadChatHistory(option.chatid);
			} else if(option.type == "new") { //创建新会话mysql 去重时只获取最早的记录
				if(option.q==""){
					this.createChat();
				}else{
					this.chatMsg=option.q;
					this.chatid=-1;
					this.handleSend();
				}
			} else{
				this.createChat();
			} 
			
			uni.onKeyboardHeightChange(res => {
				//这里正常来讲代码直接写
				//this.keyboardHeight=this.rpxTopx(res.height)就行了
				//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
				this.keyboardHeight = this.rpxTopx(res.height)
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;

			})
			this.scrollToBottom();
		},
		onShareAppMessage() {
					return {
						title: "耒耜AI大模型",
						path: '/pages/index/index',
					};
		},
		methods: {
			sendable(){
				return this.chatMsg==""? false:true;
			},
			recordingMove(event){
				var diffY=event.touches[0].clientY-this.touchY;
				if(diffY<-40){
					this.recordingTip="松手 取消";
					if(this.isCanel!=true){
						this.isCancel=true;
					}
				}else{
					this.recordingTip="按住 说话";
					if(this.isCanel!=false){
						this.isCancel=false;
					}
					
				}
			},
			startRecording(event){
				this.isRecording=true;
				console.log("开始录音");
				uni.vibrateShort();
				this.touchY=event.touches[0].clientY;
			
			},
			stopRecording(){
				this.isRecording=false;
				if(this.isCancel){
					console.log("取消录音");
				}else{
					console.log("结束录音");
					this.isCancel=false;
				}
				uni.vibrateShort();
				this.recordingTip="按住 说话";
				
				
			},
			createChat(){
				this.chatid=-1;
				this.$refs.uToast.show({
					type: 'none',
					message: "开启新会话"
				});
				this.msgList=[];
				this.msgList.push({
					sender:"ai",
					waiting:0,
					content:"你好，我是耒耜AI大模型，有什么问题可以随时问我！",
					actionVisible:1
				})
			},
			handleViewHistory(item){
				if(this.chatid==item.chatid){
					return;
				}
				this.chatid=item.chatid;
				this.loadChatHistory(item.chatid);
				this.historyVisible=false;
			},
			loadChatHistory(chatid){
				this.api.get_history_detail({chatid:chatid}).then(res => {
					  if(res.code==1){
						  this.msgList=res.list;
					  }
				})
			},
			
			openHistory() {
				this.api.get_history_list({}).then(res => {
					this.history = res.data;
				})
				this.historyVisible = true;
			},
			closeHistory() {
				this.historyVisible = false;
			},
			//复制
			copyContent(msg) {
				uni.setClipboardData({
					data: msg
				});
			},
			handleSwitchInputType() {
				this.inputType = this.inputType == 'text' ? 'voice' : 'text';
				console.log(this.inputType);
				if(this.inputType=='text'){
				   this.inputFocus=true;
				}else{
					this.inputFocus=false;
				}
			},
			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 100)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 100)
			},
			// 发送消息
			handleSend() {
				if (this.chatMsg == '') {
					return;
				}
				let obj = {
					sender: "user",
					waiting: 0,
					content: this.chatMsg
				}
				this.msgList.push(obj);
				this.waitingForResponse(this.chatMsg);
				this.chatMsg = '';
				this.scrollToBottom();
			},
			startTyping(text) {

				let currentIndex = 0;
				const typingSpeed = 10; // 打字速度，单位：毫秒
				var typedText = "";
				const timer = setInterval(() => {
					typedText += text[currentIndex];
					currentIndex++;
					this.msgList[this.msgList.length - 1].content = typedText;
					if (currentIndex >= text.length) {
						this.msgList[this.msgList.length - 1].actionVisible = true;
						clearInterval(timer);
						this.scrollToBottom()
					}
				}, typingSpeed);
			},
			waitingForResponse(msg) {
				// 创建新会话
				this.msgList.push({
					sender: 'ai',
					waiting: 1,
					actionVisible: false,
					content: ''
				});
				this.scrollToBottom();
				this.isWaiting = true;
				this.api.chat({
					newchat: false,
					chatid:this.chatid,
					content: msg,
				}).then(lres => {
					if (lres.code == 1) {
						this.isWaiting = false;
						this.msgList[this.msgList.length - 1].waiting = 0;
						this.chatid=lres.chatid;
						this.startTyping(lres.response);
						this.scrollToBottom();
					}
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;

	view,
	button,
	text,
	input,
	textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* 聊天消息 */
	.chat {
		.scroll-view {
			::-webkit-scrollbar {
				display: none;
				width: 0 !important;
				height: 0 !important;
				-webkit-appearance: none;
				background: transparent;
				color: transparent;
			}

			// background-color: orange;
			background-color: #ffffff;

			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;

				.self {
					justify-content: flex-end;
				}

				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;

					.right {
						background-color: $chatContentbgc;
					}

					.left {
						background-color: #FFFFFF;
					}

					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}

				}
			}
		}

		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 240rpx;
			background: #ffffff;
			transition: all 0.5s ease;

			.send-msg {
				display: flex;
				align-items: flex-end;
				padding: 16rpx 10rpx;
				width: 100%;
				min-height: 70rpx;
				position: fixed;
				bottom: 0;
				background: #ffffff;
				transition: all 0.1s ease;
			}

			.uni-textarea {
				width: 100%;
				padding-top: 5rpx;
				padding-bottom: 8rpx;
				border-radius: 12px;

				input {
					width: 100%;
					min-height: 60rpx;
					max-height: 500rpx;
					border-radius: 40rpx;
					font-size: 32rpx;
					color: #333333;
					line-height: 60rpx;
					padding: 5rpx 8rpx;
				}
			}
		}
	}

	/*历史会话相关样式*/
	.history-wraper {
		background-color: #fafafa;
		overflow-y: auto;
		height: 100vh;
		padding-bottom: 50px;
	}

	.history_section {
		line-height: 30px;
		height: 30px;
		padding-left: 5px;
		font-weight: bold;
	}
</style>